/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月16日
 */
package com.massyframework.beanskin.web.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContext;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.ModuleDestoryingEvent;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.AssemblyEventAdapter;
import com.massyframework.beanskin.service.ServiceFactory;
import com.massyframework.beanskin.web.ModularServletContext;

/**
 * {@link ModularServletContextFactory}提供创建{@link ServletContext}的工厂
 * @author huangkh
 *
 */
public abstract class ModularServletContextFactory extends AssemblyEventAdapter 
	implements ServiceFactory<ModularServletContext> {
	
	private ServletContext origin;
    private Map<String, ModularServletContext> contextMap;

	/**
     * 构造方法
     */
    public ModularServletContextFactory() {
        this.contextMap = new ConcurrentHashMap<>();
    }

    public void setServletContext(ServletContext origin){
        this.origin = origin;
    }

    /**
     * 获取服务实例
     *
     * @param assembly {@link Module}, 请求服务实例的装配件
     * @return {@link S}
     */
    @Override
    public final ModularServletContext getService(Module<?> module) {
	    return this.contextMap.computeIfAbsent(module.toIdentifier(),
	            name -> this.createServletContext(this.origin, module));

    }

    @Override
	protected void onDestorying(ModuleDestoryingEvent event) {
		super.onDestorying(event);
		Module<?> module = event.getModule();
		if (module instanceof Assembly) {
			Assembly assembly = (Assembly)module;
			String key = assembly.toIdentifier();
			ModularServletContext context = this.contextMap.remove(key);
			if (context != null) {
				context.clean();
			}
		}
	}
    

	/**
     * 创建ModularServletContext
     * @param origin {@link ServletContext}，原始的ServletContext
     * @param module {@link Module}, 装配件
     * @return {@link ModularServletContext}
     */
    protected abstract ModularServletContext createServletContext(ServletContext origin,  Module<?> module);
}
